import { useState } from 'react'
import place from '@/assets/pngs/03.place.png'
import { LoadingOutlined } from '@ant-design/icons'
import { useRequest } from 'ahooks'
import { useNavigate , useParams } from 'react-router-dom'
import { pageArticle } from '@/service/article'
import { useScrollLoad } from '@/hooks'
import { debounce } from 'lodash'
import readed from '@/assets/svgs/03.readed.svg'
import thumbs from '@/assets/svgs/04.thumbs-up.svg'

import "./index.less"

type PageInfo = {
  current: number,
  pageSize: number,
  total:number
}

export default function ArticleList() {

  const [pageInfo, setPageInfo] = useState<PageInfo>({current:1 , pageSize:10 , total:0});

  const [dataSource, setDataSource] = useState<App.ArticleItem[]>([]);

  const [ noMore , setNoMore ] = useState<boolean>(false)

  const navigate = useNavigate();

  const { tag } = useParams<{tag:string}>();

  const { runAsync: loadBlog } = useRequest(async ({ current = 1, pageSize = 10 } = {}) => {
    
    const { records = [], total = 0 } = await pageArticle({
      current,
      pageSize,
      tag,
    }) || {}
    setDataSource(prev => [...prev, ...records])
    setPageInfo(prev => ({ ...prev, total }));

    if (total === records.length) {
      setNoMore(true)
    }
  })

  // const [ loading , setLoading ] = useState<boolean>(false)

  useScrollLoad(debounce(async () => {
    if (pageInfo.total < dataSource.length || pageInfo.total === dataSource.length) {
      setNoMore(true)
      return
    }
    const { current } = pageInfo
    await loadBlog({ current: current + 1, pageSize: 10 })
    setPageInfo(prev => ({ ...prev, current: current + 1 }))
  },500))

  return (
    <div className="article-list">
      {
        dataSource.map(item => {
          const src = item.pic || place
          return (
            <div className="item-container" key={ item.id} onClick={()=>navigate(`/blog_detail/${item.id}`)}>
              <div className="inner-container">
                <div className="item-pic">
                  <img src={src} alt="" />
                </div>
                <div className="item-info">
                    <div className="item-title">{ item.title }</div>
                    <span>{ item.article_desc }</span>
                    <div className="item-action">
                      <div><img src={readed} />{ item.read_num }</div>
                      <div><img src={thumbs} />{ item.like_num }</div>
                    </div>
                </div>
              </div>
            </div>
          )
        })
      }
      {noMore && <div className="no-more">没有更多了</div>}
      {
        !noMore && (
          <div className="loading">
            <LoadingOutlined/> 
          </div>
        )
      }
    </div>
  )
}